﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Elderos.TextSearchers
{
	public class OntologyStringLoader : IStringLoader
	{
		private SqlConnection _connection;

		private const string QueryFormat =
@"select {0} s.syno
from Synonyms s";

		public OntologyStringLoader(string connectionString = null)
		{
			string cstring = connectionString
							 ?? ConfigurationManager.ConnectionStrings["Ontology"].ConnectionString;
			_connection = new SqlConnection(cstring);
		}

		public IEnumerable<string> LoadStrings(int? maxCount)
		{
			using (SqlCommand command = _connection.CreateCommand())
			{
				string topQueryPart = maxCount.HasValue
										  ? "top " + maxCount.Value
										  : String.Empty;

				command.CommandText = string.Format(QueryFormat, topQueryPart);
				if (_connection.State != ConnectionState.Open)
					_connection.Open();
				using (SqlDataReader reader = command.ExecuteReader())
				{
					int counter = 0;
					while (reader.Read())
					{
						counter++;

						string str = reader.GetString(0);
						if (counter % 100000 == 0)
							Console.WriteLine(counter + " string loaded.");

						yield return str;
					}
				}
			}
		}

		#region Implementation of IDisposable

		/// <summary>
		/// Выполняет определяемые приложением задачи, связанные с удалением, высвобождением или сбросом неуправляемых ресурсов.
		/// </summary>
		/// <filterpriority>2</filterpriority>
		public void Dispose()
		{
			if (_connection != null)
				_connection.Dispose();
		}

		#endregion
	}
}
